package com.draw.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class DrawRectServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //禁止页面缓存
        resp.setHeader("Pragma","No-cache");
        resp.setHeader("Cache-Control","No-cache");
        resp.setDateHeader("Expires",0);
        resp.setContentType("image/JPEG");//设置响应格式为JPEG图片
        //创建一个指定长度的图像
        int width = 240,height=180;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();//获取用于处理图形上下文的对象
        graphics.setColor(new Color(221,221,221));//设置第一个矩形的RGB颜色
        graphics.fillRect(0,0,240,180);//设置实心矩形
        graphics.setColor(Color.BLACK);//设置第二个矩形的颜色
        graphics.drawRect(30,40,80,60);//绘制空心矩形，四个参数依序是左上角x坐标，左上角y坐标，矩形宽度，矩形高度
        graphics.setColor(new Color(178,186,174));//设置第三个矩形的RGB颜色
        graphics.fillRect(140,40,80,60);//绘制实心矩形
        graphics.dispose();//释放次图形的上下文以及它使用的所有系统资源
        ImageIO.write(image,"JPEG",resp.getOutputStream());//输出JPEG格式图片到页面
        resp.getOutputStream().flush();//刷新输出流
        resp.getOutputStream().close();//关闭输出流
    }
}
